﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace DbTeleportáció
{
    /// <summary>
    /// Various extension methods used withing this application
    /// </summary>
    /// <remarks>
    /// -------------------------------------------Change Log---------------------------------------------
    /// 04/01/2016 - DCS - Created
    /// --------------------------------------------------------------------------------------------------
    /// </remarks>
    static class Extensions
    {
        /// <summary>
        /// Attemps to open a SqlConnection object, returning an appropriate exit code if opening fails
        /// </summary>
        /// <param name="conn">Connection to attempt to open</param>
        public static void TryOpen(this SqlConnection conn)
        {
            if (conn.State == System.Data.ConnectionState.Open)
            {
                return;
            }

            try
            {
                conn.Open();
            }
            catch (Exception)
            {
                Environment.ExitCode = (int)ExitCodes.UnableToConnectToDatabaseOrInvalidConnectionString;
                throw;
            }
        }

        /// <summary>
        /// Removes invalid characters to produce a valid file name
        /// </summary>
        /// <param name="fileName">Filename to clean</param>
        /// <returns>Filename containing only valid characters</returns>
        public static string CleanFileName(this string fileName)
        {
            Regex invalidChars = new Regex(@"[^a-zA-Z0-9_\-\.\s]");
            return invalidChars.Replace(fileName, "_");
        }
    }
}
